package cn.ava.pet.listener;

import cn.ava.order.domain.OrderPetAcquisition;
import cn.ava.pet.domain.SearchMasterMsg;
import cn.ava.pet.mapper.SearchMasterMsgMapper;
import com.alibaba.fastjson.JSONObject;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * rocketmq 消息监听，@RocketMQMessageListener中的selectorExpression为tag，默认为*
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "delay_order_topic",selectorExpression="*",consumerGroup = "delay_order_group")
public class RocketMQMsgListener implements RocketMQListener<MessageExt> {

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Override
    public void onMessage(MessageExt message) {
        byte[] body = message.getBody();
        String msg = new String(body, CharsetUtil.UTF_8);
        // 把获取到的JSON字符串转换为对象
        OrderPetAcquisition orderPetAcquisition = JSONObject.parseObject(msg, OrderPetAcquisition.class);
        // 根据id获取订单信息
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.getById(orderPetAcquisition.getSearchMasterMsgId());
        // 判断状态是否为未处理
        Integer state = searchMasterMsg.getState();
        if (state == 0) {
            // 如果是,那么直接置空商家id,放回寻主池
            searchMasterMsg.setShopId(null);
            // 修改数据
            searchMasterMsgMapper.update(searchMasterMsg);
        }
        String result = state == 1 ? "已完成" : (state == 0 ? "待处理" : "取消");
        log.warn("接收到消息：{}",result);
    }

}
